package com.css.fxfzypg.modules.baseData.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.common.utils.UpdateUtil;
import com.css.fxfzypg.common.utils.excel.ExcelReaderUtil;
import com.css.fxfzypg.common.utils.excel.ExcelResult;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.entity.CountiesCondition;
import com.css.fxfzypg.modules.baseData.entity.VillageTownCondition;
import com.css.fxfzypg.modules.baseData.queryParams.VillageTownConditionQueryParams;
import com.css.fxfzypg.modules.baseData.repository.VillageTownConditionRepository;
import com.css.fxfzypg.modules.baseData.service.VillageTownConditionService;
import com.css.fxfzypg.modules.baseData.vo.CountiesConditionVO;
import com.css.fxfzypg.modules.baseData.vo.VillageTownConditionVO;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Dbj
 * @date 2022年11月14日  10:21
 */
@Service
@Slf4j
public class VillageTownConditionServiceImpl implements VillageTownConditionService {

    @Resource
    private VillageTownConditionRepository villageTownConditionRepository;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private SysAreaService sysAreaService;
    @Resource
    AttachmentInfoService attachmentInfoService;

    @Override
    public JSONObject getAllVillageTownCondition(VillageTownConditionQueryParams queryParams, int curPage, int pageSize) {
        return villageTownConditionRepository.getAllVillageTownCondition(queryParams,curPage, pageSize);
    }

    @Override
    public void saveVillageTownCondition(VillageTownCondition villageTownCondition) throws Exception{
        Map<String,String> areaIdCodeMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaIdCodeMap"));
        //查询库是否有该省市县的数据
        int total =  villageTownConditionRepository.getVillageTownConditionBydivision(villageTownCondition.getProvinceId(),
                villageTownCondition.getCityId(), villageTownCondition.getPrefectureId(),villageTownCondition.getVillageTown());
        if (total>0) {
            throw new RuntimeException("该省市县乡镇已存在，请去修改！！");
        }

        String divisionNames = null;
        try {
            //根据省市县Id,获取省市县名称;单个id可以获得单个名称;多个id，用逗号分割，可以获得多个名称
            String divisionIds = villageTownCondition.getProvinceId() + "," + villageTownCondition.getCityId() + "," + villageTownCondition.getPrefectureId();
            divisionNames = sysAreaService.getAreaNameByAreaId(divisionIds);
        } catch (Exception e) {
            throw new RuntimeException("省市县的id不符合符合规范！");
        }
        String[] split = divisionNames.split(",");
        villageTownCondition.setProvince(split[0]);
        if (split.length == 2) {
            villageTownCondition.setCity(split[0]);
            villageTownCondition.setPrefecture(split[1]);
        } else {
            villageTownCondition.setCity(split[1]);
            villageTownCondition.setPrefecture(split[2]);
        }
        StringBuilder erorrMessage = getMessage(villageTownCondition);

        villageTownCondition.setCcId(UUIDGenerator.getUUID());
        villageTownCondition.setCreateUser(PlatformSessionUtils.getUserId());
        villageTownCondition.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        villageTownCondition.setIsDelete(YNEnum.N.toString());
        villageTownCondition.setProvinceCode(areaIdCodeMap.get(villageTownCondition.getProvinceId()));
        villageTownCondition.setCityCode(areaIdCodeMap.get(villageTownCondition.getCityId()));
        villageTownCondition.setPrefectureCode(areaIdCodeMap.get(villageTownCondition.getPrefectureId()));
        if (erorrMessage.length() < 1) {
            int i = villageTownConditionRepository.saveVillageTownCondition(villageTownCondition);
        }
    }

    /**
     * 对实体类数据进行校验
     *
     * @param entity 实体类
     * @return 错误信息
     */
    private StringBuilder getMessage(VillageTownCondition entity) {
        StringBuilder erorrMessage = new StringBuilder();
        if (PlatformObjectUtils.isEmpty(entity.getCcLandform())) {
            erorrMessage.append("地形地貌特征 不能为空！ ");
        } else {
            if (entity.getCcLandform().length() > 500) {
                erorrMessage.append("地形地貌特征 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcSeismotectonics())) {
            erorrMessage.append("地震构造特征 不能为空！ ");
        } else {
            if (entity.getCcSeismotectonics().length() > 500) {
                erorrMessage.append("地震构造特征 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcClimate())) {
            erorrMessage.append("气候特征 不能为空！ ");
        } else {
            if (entity.getCcClimate().length() > 500) {
                erorrMessage.append("气候特征 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcNation())) {
            erorrMessage.append("人口民族特性 不能为空！ ");
        } else {
            if (entity.getCcNation().length() > 500) {
                erorrMessage.append("人口民族特性 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcEconomy())) {
            erorrMessage.append("经济产业特性 不能为空！ ");
        } else {
            if (entity.getCcEconomy().length() > 500) {
                erorrMessage.append("经济产业特性 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcTraffic())) {
            erorrMessage.append("交通情况 不能为空！ ");
        } else {
            if (entity.getCcTraffic().length() > 500) {
                erorrMessage.append("交通情况 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcDisaster())) {
            erorrMessage.append("地质灾害情况 不能为空！ ");
        } else {
            if (entity.getCcDisaster().length() > 500) {
                erorrMessage.append("地质灾害情况 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcFacility())) {
            erorrMessage.append("基础设施 不能为空！ ");
        } else {
            if (entity.getCcFacility().length() > 500) {
                erorrMessage.append("基础设施 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcTrait())) {
            erorrMessage.append("其他区域特点 不能为空！ ");
        } else {
            if (entity.getCcTrait().length() > 500) {
                erorrMessage.append("其他区域特点 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcSchool())) {
            erorrMessage.append("主要中小学信息统计 不能为空！ ");
        } else {
            if (entity.getCcSchool().length() > 500) {
                erorrMessage.append("主要中小学信息统计 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcHospital())) {
            erorrMessage.append("主要医院信息统计 不能为空！ ");
        } else {
            if (entity.getCcHospital().length() > 500) {
                erorrMessage.append("主要医院信息统计 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcHazard())) {
            erorrMessage.append("重大危险源统计 不能为空！ ");
        } else {
            if (entity.getCcHazard().length() > 500) {
                erorrMessage.append("重大危险源统计 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcReservoir())) {
            erorrMessage.append("水库信息统计 不能为空！ ");
        } else {
            if (entity.getCcReservoir().length() > 500) {
                erorrMessage.append("水库信息统计 不能超过500字！ ");
            }
        }
        if (PlatformObjectUtils.isEmpty(entity.getCcMessage())) {
            erorrMessage.append("综合信息 不能为空！ ");
        } else {
            if (entity.getCcMessage().length() > 500) {
                erorrMessage.append("综合信息 不能超过500字！ ");
            }
        }
        return erorrMessage;
    }

    @Override
    public VillageTownConditionVO getVillageTownConditionById(String id) {
        VillageTownCondition villageTownCondition = villageTownConditionRepository.getVillageTownConditionById(id);
        VillageTownConditionVO countiesConditionVO = new VillageTownConditionVO();
        UpdateUtil.copyNullProperties(villageTownCondition, countiesConditionVO);
        countiesConditionVO.setVillageTown(villageTownCondition.getVillageTown());
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcLandformAttachment())) ;
        countiesConditionVO.setCcLandformAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcLandformAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcSeismotectonicsAttachment()))
            countiesConditionVO.setCcSeismotectonicsAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcSeismotectonicsAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcClimateAttachment()))
            countiesConditionVO.setCcClimateAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcClimateAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcNationAttachment()))
            countiesConditionVO.setCcNationAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcNationAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcEconomyAttachment()))
            countiesConditionVO.setCcEconomyAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcEconomyAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcTrafficAttachment()))
            countiesConditionVO.setCcTrafficAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcTrafficAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcDisasterAttachment()))
            countiesConditionVO.setCcDisasterAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcDisasterAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcFacilityAttachment()))
            countiesConditionVO.setCcFacilityAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcFacilityAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcTraitAttachment()))
            countiesConditionVO.setCcTraitAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcTraitAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcSchoolAttachment()))
            countiesConditionVO.setCcSchoolAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcSchoolAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcHospitalAttachment()))
            countiesConditionVO.setCcHospitalAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcHospitalAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcHazardAttachment()))
            countiesConditionVO.setCcHazardAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcHazardAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcReservoirAttachment()))
            countiesConditionVO.setCcReservoirAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcReservoirAttachment()));
        if (PlatformObjectUtils.isNotEmpty(villageTownCondition.getCcMessageAttachment()))
            countiesConditionVO.setCcMessageAttachment(attachmentInfoService.queryFile(villageTownCondition.getCcMessageAttachment()));
        return countiesConditionVO;
    }

    @Override
    public void delete(String id) {
        String userId = PlatformSessionUtils.getUserId();
        Timestamp timestamp = PlatformDateUtils.getCurrentTimestamp();
        villageTownConditionRepository.delete(id, timestamp, userId);
    }

    @Override
    public void update(VillageTownCondition villageTownCondition) {
        //数据判断是否符合要求
        StringBuilder message = getMessage(villageTownCondition);
        if (message.length() > 0) {
            throw new RuntimeException(String.valueOf(message));
        }
        VillageTownCondition villageTownConditionById = villageTownConditionRepository.getVillageTownConditionById(villageTownCondition.getCcId());
        //把countiesConditionById(通过Id查询)原实体，只赋值到countiesCondition目标实体的空值，
        UpdateUtil.copyNullProperties(villageTownConditionById, villageTownCondition);
        villageTownCondition.setUpdateUser(PlatformSessionUtils.getUserId());
        villageTownCondition.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        villageTownConditionRepository.update(villageTownCondition);
    }

    @Override
    public RestResponse excelImport(MultipartFile file) throws Exception{
        List<VillageTownCondition> entityList = new ArrayList<>();
        ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), VillageTownCondition.class);
        StringBuilder message = new StringBuilder(excelResult.getMessage());
        if (excelResult.getData().size() == 0) {
            return ResponseCreator.createFailResponse( message.toString());
        }
        for (Object datum : excelResult.getData()) {
            VillageTownCondition entity = (VillageTownCondition) datum;
            String divisionIds = null;
            try {
                //判断省市县的名称是否符合规范
                divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(entity.getProvince(), "utf-8"),
                        URLEncoder.encode(entity.getCity(), "utf-8"),
                        URLEncoder.encode(entity.getPrefecture(), "utf-8"));
            } catch (Exception e) {
                message.append(entity.getProvince() + "," + entity.getCity() + "," + entity.getPrefecture() + " 省市县的名称不规范.<br/>");
                continue;
            }
            String[] s = divisionIds.split("_");
            if (s.length!=3) {
                message.append(entity.getProvince() + "," + entity.getCity() + "," + entity.getPrefecture() + " 省市县的名称不规范.<br/>");
                continue;
            }
            entityList.add(entity);
        }
        if (entityList.size()==0){
            return ResponseCreator.createSuccessResponse(null, message.toString());
        }
        if (message.toString().length()>0){
            return ResponseCreator.createSuccessResponse(null, message.toString());
        }
        for (VillageTownCondition condition : entityList) {
            //根据省市区查数据库
            VillageTownCondition hosPeo = villageTownConditionRepository.getVillageCountiesCodition(condition.getProvince(), condition.getCity(), condition.getPrefecture(),condition.getVillageTown());
            if (hosPeo != null) {
                message.append(hosPeo.getProvince() + "," + hosPeo.getCity() + "," + hosPeo.getPrefecture() + ","+hosPeo.getVillageTown()+" 该省市区乡镇下已有数据,确认是否需要覆盖<br/>");
            }
        }
        if (message.toString().length() > 0) {
            return ResponseCreator.createSuccessResponse(entityList, message.toString());
        }
        for (VillageTownCondition entity : entityList) {
            save(entity);
        }
        return ResponseCreator.createSuccessResponse(null,"成功导入"+entityList.size()+"条.");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cover(List<VillageTownCondition> list) {
        for (VillageTownCondition condition : list) {
            villageTownConditionRepository.deleteByVillageTown(condition);
            save(condition);
        }
    }

    private void save(VillageTownCondition entity){
        String divisionIds = null;
        try {
            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(entity.getProvince(), "utf-8"),
                    URLEncoder.encode(entity.getCity(), "utf-8"),
                    URLEncoder.encode(entity.getPrefecture(), "utf-8"));
            String[] split = divisionIds.split("_");
            entity.setProvinceId(split[0]);
            entity.setCityId(split[1]);
            entity.setPrefectureId(split[2]);
        } catch (UnsupportedEncodingException e) {
            log.info(e.getMessage());
        }
        entity.setIsDelete(YNEnum.N.toString());
        entity.setCreateUser(PlatformSessionUtils.getUserId());
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        try {
            Map<String, String> areaIdCodeMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
            entity.setProvinceCode(areaIdCodeMap.get(entity.getProvinceId()));
            entity.setCityCode(areaIdCodeMap.get(entity.getCityId()));
            entity.setPrefectureCode(areaIdCodeMap.get(entity.getPrefectureId()));
        } catch (Exception e) {
            log.info("获取省市区code码错误");
        }
        entity.setCcId(UUIDGenerator.getUUID());
        villageTownConditionRepository.saveVillageTownCondition(entity);
    }


}
